<?php
header('Content-Type: application/json');

try {
    // 读取请求数据
    $data = json_decode(file_get_contents('php://input'), true);
    if (!isset($data['id']) || !isset($data['direction'])) {
        throw new Exception('参数错误');
    }

    // 读取英雄数据
    $heroesFile = '../../data/heroes.json';
    if (!file_exists($heroesFile)) {
        throw new Exception('数据文件不存在');
    }

    $heroes = json_decode(file_get_contents($heroesFile), true);
    if (!isset($heroes['heroes'])) {
        throw new Exception('数据格式错误');
    }

    // 按 sort 字段排序
    usort($heroes['heroes'], function($a, $b) {
        return $a['sort'] - $b['sort'];
    });

    // 找到当前英雄的索引
    $currentIndex = -1;
    foreach ($heroes['heroes'] as $index => $hero) {
        if ($hero['id'] === $data['id']) {
            $currentIndex = $index;
            break;
        }
    }

    if ($currentIndex === -1) {
        throw new Exception('英雄不存在');
    }

    // 根据方向交换位置
    if ($data['direction'] === 'up' && $currentIndex > 0) {
        // 交换 sort 值
        $temp = $heroes['heroes'][$currentIndex]['sort'];
        $heroes['heroes'][$currentIndex]['sort'] = $heroes['heroes'][$currentIndex - 1]['sort'];
        $heroes['heroes'][$currentIndex - 1]['sort'] = $temp;
    } else if ($data['direction'] === 'down' && $currentIndex < count($heroes['heroes']) - 1) {
        // 交换 sort 值
        $temp = $heroes['heroes'][$currentIndex]['sort'];
        $heroes['heroes'][$currentIndex]['sort'] = $heroes['heroes'][$currentIndex + 1]['sort'];
        $heroes['heroes'][$currentIndex + 1]['sort'] = $temp;
    }

    // 保存回文件
    if (file_put_contents($heroesFile, json_encode($heroes, JSON_PRETTY_PRINT))) {
        echo json_encode(['success' => true]);
    } else {
        throw new Exception('保存失败');
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?> 